import fs from "fs-extra";
import path from "path";
import { ITerserCache } from "../typings";

export class JsTerser {
    public async terserAll(dir: string, cache: ITerserCache): Promise<void> {
        const files = await fs.readdir(dir);
        for (const f of files) {
            const file = path.join(dir, f);
            const fstat = await fs.stat(file);
            if (fstat.isDirectory()) {
                await this.terserAll(file, cache);
            } else {
                if (path.extname(f) === '.js') {
                    let content = await fs.readFile(file, 'utf-8');
                    for (const k in cache) {
                        content = content.replaceAll(new RegExp('\\b' + k + '\\b', 'g'), cache[k]);
                    }
                    await fs.writeFile(file, content);
                }
            }
        }
    }
}
